package com.yuanqi.Service.Impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yuanqi.Common.Pojo.Vo.*;
import com.yuanqi.Common.Pojo.entity.*;
import com.yuanqi.Common.config.ThreadLocalConfig;
import com.yuanqi.Mapper.FollowMapper;
import com.yuanqi.Mapper.ImageMapper;
import com.yuanqi.Mapper.PostMapper;
import com.yuanqi.Mapper.UserMapper;
import com.yuanqi.Common.Pojo.Dto.PostDto;
import com.yuanqi.Service.PostService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

@Service
public class PostServiceImpl extends ServiceImpl<PostMapper, Post> implements PostService {
    @Resource
    PostMapper postMapper;
    @Resource
    ImageMapper imageMapper;
    @Resource
    ThreadLocalConfig threadLocalConfig;
    @Resource
    UserMapper userMapper;
    @Resource
    FollowMapper followMapper;

    @Override
    public List<PostClass> getList() {
        return postMapper.selectclasslist();
    }

    @Override
    public Image SaveImage(String upload) {
        String id = threadLocalConfig.get().get("userId").toString();
//        String id = "400";
        Image build = Image.builder().url(upload).userId(Integer.parseInt(id)).createTime(System.currentTimeMillis()).build();
        imageMapper.insert(build);
        return build;
    }

    @Override
    public void publish(PostDto postdto) {
//先保存文章
        Post post = BeanUtil.toBean(postdto, Post.class);
        //查询第一张图片作为封面图
        if (!CollectionUtil.isEmpty(postdto.getImageId())) {
            Image image = imageMapper.selectById(postdto.getImageId().get(0));
            post.setTitlepic(image.getUrl());

        }
        //设置开头
        post.setTitle(postdto.getContent().split(",")[0]);
        //设置用户
        post.setUserId(Long.parseLong(threadLocalConfig.get().get("userId").toString()));
        //设置时间
        post.setCreateTime(System.currentTimeMillis() / 1000);
        post.setType(1L);
        //保存文章
        postMapper.insert(post);
        //保存图片与文章的关联
        Long time = System.currentTimeMillis() / 1000;

        if (!CollectionUtil.isEmpty(postdto.getImageId())) {
            for (Long id : postdto.getImageId()) {
                postMapper.saveImagePost(post.getId(), id, time);
            }
        }

        //保存文章与话题的关联
        postMapper.savePostTopic(post.getId(), postdto.getTopicId(), time);

    }

    @Override
    public PostDetail getDetail(Long id) {
        //先查询文章
        Post post = postMapper.selectById(id);
        if (post == null) {
            return null;
        }
//        通过userId查询发布用户
        //通过文章查询图片
        List<String> list = postMapper.selectImage(post.getId());
        //查询分享
        Post share = postMapper.selectById(post.getShareId());
        return new PostDetail(post, null, list, share);
    }

    @Override
    public List<PostVo> getPostByClassId(Long id, Integer current, Long UserId) {

        Integer start = (current - 1) * 5;
        List<PostVo> list = postMapper.selectPostAndCommentCountByPostId(id, start);
        extracted(list, 0, UserId);
        return list;
    }


    @Override
    public List<PostVo> getPostByUserId(Long userid, Integer current, Long loginUserId) {
        Integer start = (current - 1) * 5;
        List<PostVo> list = postMapper.selectPostAndCommentCountByUserId(userid, start, 0);
        extracted(list, 0, loginUserId);
        return list;
    }

    @Override
    public List<PostVo> getPostByLoginUser() {
        Long userId = Long.parseLong(threadLocalConfig.get().get("userId").toString());
        List<PostVo> list = postMapper.selectPostAndCommentCountByUserId(userId, null, 1);
        extracted(list, 1, null);
        return list;
    }

    @Override
    public List<PostVo> SearchPost(PostDto postDto) {
        Integer start = (postDto.getCurrent() - 1) * 10;
        List<PostVo> records = postMapper.searchPostBytitle(postDto.getTitle(), start);
        if (records.isEmpty()) {
            return records;
        }
        extracted(records, 0, postDto.getUserId());
        return records;
    }

    @Override
    public List<PostVo> getconcernpost(Integer current) {
         Integer start = (current- 1) * 10;
          Long userId = Long.parseLong(threadLocalConfig.get().get("userId").toString());

      List<PostVo> records =  postMapper.getconcernpost(start,userId);
       if (records.isEmpty()) {
            return records;
        }
       extracted(records, 0,userId);
        return records;
    }

    //获取用户和顶踩
    void extracted(List<PostVo> list, Integer isUser, Long userId) {
        if (CollectionUtil.isEmpty(list)) {
            return;
        }
        //去除我拉黑的用户和我被拉黑的用户
        ArrayList<Long> LaHeiUserId = new ArrayList<>();

        if (userId != null) {
            List<Long> blacklists = postMapper.selectLaheiUserId(userId);
            List<Long> beilaheiList = postMapper.selectBeiLaheiUserId(userId);
            LaHeiUserId.addAll(blacklists);
            LaHeiUserId.addAll(beilaheiList);
        }


        Iterator<PostVo> iterator = list.iterator();

        while (iterator.hasNext()) {
            PostVo post = iterator.next();
//            把拉黑的列表删除了
            if (LaHeiUserId.contains(post.getUserId())) {
                iterator.remove();
                continue;
            }
            if (isUser == 0) {
                User user = userMapper.selectById(post.getUserId());
                UserVo userVo = BeanUtil.toBean(user, UserVo.class);
                post.setUser(userVo);
            }

            List<Support> supports = postMapper.selectSupport(post.getId());
            SupportVo supportVo = new SupportVo();
            if (!supports.isEmpty()) {
                supports.forEach(support -> {
                    if (support.getType() == 1) {
                        supportVo.setSupport(support.getCount());
                    } else if (support.getType() == 0) {
                        supportVo.setUnSupportCount(support.getCount());
                    }
                });
            }

            //这是防止用户没有登录
            if (userId == null) {
                post.setIsFollow(0);
                supportVo.setUserSupportType(null);
                post.setSupportVo(supportVo);
            } else {
                LambdaQueryWrapper<Follow> wrapper = new LambdaQueryWrapper<Follow>().eq(Follow::getUserId, userId).eq(Follow::getFollowId, post.getUserId());
                List<FollowVo> followVos = followMapper.eachOther(userId, 0);
                Follow follow1 = followMapper.selectOne(wrapper);
                if (ObjectUtil.isEmpty(follow1)) {
                    post.setIsFollow(0);
                } else {
                    post.setIsFollow(1);
                }
                if (!followVos.isEmpty()&&follow1!=null) {
                    followVos.forEach(followVo -> {
                        if (followVo.getFollowId().equals(follow1.getFollowId())) {
                            post.setIsFollow(2);
                        }
                    });
                }

                Integer type = postMapper.selectUserSupport(userId, post.getId());
                supportVo.setUserSupportType(type);
                post.setSupportVo(supportVo);
            }


        }
    }
}
